<template>
  <div class="email_menu_wrap">
    <div class="filter_con">
      <el-dropdown trigger="click" @command="handleFilter">
        <i v-if="!filter.show" class="iconfont icon-shaixuan" />
        <span v-else>
          <i class="iconfont icon-close" @click.stop="handlerClearFilter" />
          {{filter.name}}
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="unread">仅未读</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="scroll" ref="scrollContainerRef" @scroll="handleScroll">
      <div v-loading="true" element-loading-svg-view-box="0, 0, 1024, 1024" :element-loading-svg="LoadingSvg" v-if="loading" class="loading"></div>
      <EmailList :currentMessageId="currentMessageId" ref="emailListRef" @setUserBG="setUserBG" @isReadyUpdateFolderNum="isReadyUpdateFolderNum"  :filterParams="filterParams" :searchList="props.searchList" @refresh="handlerRefresh" :refreshKey="curAccount + curFolder" />
    </div>
  </div>
</template>
<script lang="ts" setup name="">
import { ref, defineProps, nextTick, defineEmits, onMounted, onUnmounted } from 'vue';
import { storeToRefs } from 'pinia';
import { useEmail } from '/@/stores/email';
import pinia from '/@/stores/index';

import EmailList from './emailList.vue';
import { LoadingSvg } from '/@/utils/loading';

const props = defineProps({
  searchList: {
    type: Object,
    default: null,
  },
  currentMessageId: {
    type: [String, Number],
    default: ''
  },
});

const setUserBG = (messageId:string, color:string) => emit('setUserBG', messageId, color);


const emit = defineEmits(['refresh', 'isReadyUpdateFolderNum', 'setUserBG']);
const loading = ref(false);
const scrollContainerRef = ref<any>();
const emailListRef = ref();
const filterParams = ref<any>({});
const filter = ref<any>({show: false, name: ''});

const stores = useEmail(pinia);
const { curAccount, curFolder } = storeToRefs(stores);
const refreshThreshold = 20; // 增加刷新阈值到20像素
const lastScrollTop = ref(0);
const startY = ref(0);
const isPulling = ref(false);
const pullDistance = ref(0);

// 触摸开始
const handleTouchStart = (e: TouchEvent) => {
  console.log("触摸开始:", e);
  if (scrollContainerRef.value && scrollContainerRef.value.scrollTop === 0) {
    startY.value = e.touches[0].clientY;
    isPulling.value = true;
    e.preventDefault(); // 阻止默认滚动行为
    console.log("开始下拉刷新");
  }
};

// 触摸移动
const handleTouchMove = (e: TouchEvent) => {
  console.log("触摸移动:", e, "isPulling:", isPulling.value);
  if (isPulling.value) {
    e.preventDefault(); // 阻止默认滚动行为
    const currentY = e.touches[0].clientY;
    pullDistance.value = currentY - startY.value;
    console.log("下拉距离:", pullDistance.value);
    
    // 只有向下拉才触发刷新
    if (pullDistance.value > 50) {
      console.log("触发刷新");
      handleRefreshTrigger();
      isPulling.value = false;
    }
  }
};

// 触摸结束
const handleTouchEnd = (e: TouchEvent) => {
  console.log("触摸结束");
  if (isPulling.value) {
    e.preventDefault();
  }
  isPulling.value = false;
  pullDistance.value = 0;
};

// 组件挂载后绑定原生事件监听器
onMounted(() => {
  if (scrollContainerRef.value) {
    scrollContainerRef.value.addEventListener('touchstart', handleTouchStart, { passive: false });
    scrollContainerRef.value.addEventListener('touchmove', handleTouchMove, { passive: false });
    scrollContainerRef.value.addEventListener('touchend', handleTouchEnd, { passive: false });
  }
});

// 组件卸载时清理事件监听器
onUnmounted(() => {
  if (scrollContainerRef.value) {
    scrollContainerRef.value.removeEventListener('touchstart', handleTouchStart);
    scrollContainerRef.value.removeEventListener('touchmove', handleTouchMove);
    scrollContainerRef.value.removeEventListener('touchend', handleTouchEnd);
  }
});

// 统一的刷新触发函数
const handleRefreshTrigger = () => {
  if (loading.value) return;
  
  loading.value = true;
  if (emailListRef.value) {
    emailListRef.value.refresh();
  }
  setTimeout(() => loading.value = false, 1500);
};

const handleScroll = () => {
  console.log('scroll')
  if (loading.value) {
    return;
  }
  if (scrollContainerRef.value) {
    const scrollTop = scrollContainerRef.value.scrollTop;

    // 改进的下拉刷新逻辑：
    // 1. 当滚动到顶部附近时（scrollTop <= refreshThreshold）
    // 2. 并且是向上滚动或者已经在顶部（scrollTop <= lastScrollTop.value 或 scrollTop === 0）
    if (scrollTop <= refreshThreshold && (scrollTop <= lastScrollTop.value || scrollTop === 0)) {
      // 如果已经在最顶部（scrollTop === 0），直接允许刷新
      // 或者如果是向上滚动到阈值范围内，也允许刷新
      if (scrollTop === 0 || scrollTop <= lastScrollTop.value) {
        loading.value = true;
        if (emailListRef.value) {
          emailListRef.value.refresh();
        }
        setTimeout(() => loading.value = false, 1500);
      }
    }

    lastScrollTop.value = scrollTop;
  }
};


const handlerToSwitchStatus = (status:string, messageId: string) => {
  console.log('handlerToSwitchStatus2', status, messageId)
  emailListRef.value.handlerToSwitchStatus(status, messageId);
};

const handlerRefresh = () => {
  emit('refresh');
};

const isReadyUpdateFolderNum = () => {
  emit('isReadyUpdateFolderNum');
}

const refresh = () => {
  if (emailListRef.value) {
    emailListRef.value.refresh();
  }
}

const handleFilter = (command: string) => {
  if (command === 'unread') {
    filterParams.value.isSeen = false;
    filter.value.name = '仅未读';
  }
  filter.value.show = true;

  refresh();
};

const handlerClearFilter = (event: any) => {
  filter.value.show = false;
  filterParams.value = {};
  nextTick(() => refresh());
}

defineExpose({ refresh, handlerToSwitchStatus });
</script>
<style lang="scss" scoped>
.email_menu_wrap { 
  width: 300px;
  height: 100%;
  font-size: 12px;
  border-right: 1px solid #929aa2;
  user-select: none;
  background: #fff;

  .scroll {
    height: calc( 100% - 36px );
    overflow: auto;
    touch-action: none; // 添加此行
    touch-action: pan-y; /* 允许垂直滚动，禁用其他触摸手势 */

  }

  .loading {
    height: 20px;
  }
}

.filter_con {
  padding: 10px 20px;

  .icon-shaixuan, .icon-close {
    font-size: 14px;
    cursor: pointer;
    &:hover {
      color: #3B7AEE;
    }
  }
}
</style>